using Microsoft.AspNetCore.Mvc;
using SPI.AgentServer.Services.AI;
using SPI.AgentServer.Models;
using Swashbuckle.AspNetCore.Annotations;

namespace SPI.AgentServer.Controllers;

/// <summary>
/// 测试控制器 - 用于测试大模型连接和基础功能
/// </summary>
[ApiController]
[Route("api/test")]
[Produces("application/json")]
[SwaggerTag("测试功能 - 测试大模型连接和基础对话")]
public class TestController : ControllerBase
{
    private readonly IQwenClient _qwenClient;
    private readonly ILogger<TestController> _logger;

    public TestController(IQwenClient qwenClient, ILogger<TestController> logger)
    {
        _qwenClient = qwenClient;
        _logger = logger;
    }

    /// <summary>
    /// 测试大模型简单对话
    /// </summary>
    /// <remarks>
    /// 发送一个简单的消息给大模型，测试连接是否正常
    /// </remarks>
    /// <param name="message">要发送的消息</param>
    /// <returns>大模型的回复</returns>
    [HttpPost("chat")]
    [ProducesResponseType(typeof(ChatTestResponse), StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status500InternalServerError)]
    [SwaggerOperation(
        Summary = "测试大模型对话",
        Description = "发送简单消息给 Qwen 大模型，不涉及工具调用",
        OperationId = "TestChat",
        Tags = new[] { "测试功能" }
    )]
    public async Task<IActionResult> TestChat([FromBody] ChatTestRequest request)
    {
        try
        {
            _logger.LogInformation("Testing chat with message: {Message}", request.Message);

            // 构建简单的提示词
            var prompt = request.Message;

            // 调用大模型
            var response = await _qwenClient.GetStructuredResponseAsync(prompt);

            return Ok(new ChatTestResponse
            {
                Success = true,
                Request = request.Message,
                Response = response.DirectAnswer ?? "大模型未返回直接回复",
                RawResponse = response
            });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error testing chat");
            return StatusCode(500, new ChatTestResponse
            {
                Success = false,
                Request = request.Message,
                Error = ex.Message,
                ErrorDetails = ex.ToString()
            });
        }
    }

    /// <summary>
    /// 测试原始 Qwen API 调用
    /// </summary>
    /// <remarks>
    /// 直接调用 Qwen API，返回原始响应
    /// </remarks>
    [HttpPost("raw-qwen")]
    [ProducesResponseType(typeof(RawQwenTestResponse), StatusCodes.Status200OK)]
    [SwaggerOperation(
        Summary = "测试原始 Qwen API",
        Description = "直接调用 Qwen API，查看原始请求和响应",
        OperationId = "TestRawQwen",
        Tags = new[] { "测试功能" }
    )]
    public async Task<IActionResult> TestRawQwen([FromBody] ChatTestRequest request)
    {
        try
        {
            _logger.LogInformation("Testing raw Qwen API with message: {Message}", request.Message);

            var qwenRequest = new QwenRequest
            {
                Model = "Qwen2.5-VL-7B-Instruct",
                Messages = new List<QwenMessage>
                {
                    new QwenMessage
                    {
                        Role = "user",
                        Content = request.Message
                    }
                },
                MaxTokens = 500,
                Temperature = 0.7
            };

            // 使用反射调用 QwenClient 的 ChatCompletionAsync 方法
            var qwenClientType = _qwenClient.GetType();
            var method = qwenClientType.GetMethod("ChatCompletionAsync");

            if (method != null)
            {
                var task = (Task<QwenResponse>)method.Invoke(_qwenClient, new object[] { qwenRequest, CancellationToken.None });
                var qwenResponse = await task;

                return Ok(new RawQwenTestResponse
                {
                    Success = true,
                    Request = qwenRequest,
                    Response = qwenResponse
                });
            }
            else
            {
                return StatusCode(500, new RawQwenTestResponse
                {
                    Success = false,
                    Error = "无法找到 ChatCompletionAsync 方法"
                });
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error testing raw Qwen API");
            return StatusCode(500, new RawQwenTestResponse
            {
                Success = false,
                Error = ex.Message,
                ErrorDetails = ex.ToString()
            });
        }
    }

    /// <summary>
    /// 测试网络连接
    /// </summary>
    [HttpGet("connection")]
    [SwaggerOperation(
        Summary = "测试网络连接",
        Description = "测试到 Qwen API 服务器的网络连接",
        OperationId = "TestConnection",
        Tags = new[] { "测试功能" }
    )]
    public async Task<IActionResult> TestConnection()
    {
        try
        {
            var baseUrl = "http://188.18.57.151:23333";

            _logger.LogInformation("Testing connection to: {BaseUrl}", baseUrl);

            using var httpClient = new HttpClient();
            httpClient.Timeout = TimeSpan.FromSeconds(10);

            var startTime = DateTime.Now;
            var response = await httpClient.GetAsync($"{baseUrl}/v1/models");
            var endTime = DateTime.Now;

            var responseTime = (endTime - startTime).TotalMilliseconds;

            return Ok(new
            {
                success = true,
                url = baseUrl,
                statusCode = (int)response.StatusCode,
                statusText = response.StatusCode.ToString(),
                responseTime = $"{responseTime}ms",
                isSuccess = response.IsSuccessStatusCode
            });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Connection test failed");
            return Ok(new
            {
                success = false,
                error = ex.Message,
                errorType = ex.GetType().Name,
                details = ex.ToString()
            });
        }
    }
}

// 请求和响应模型
public class ChatTestRequest
{
    public string Message { get; set; } = string.Empty;
}

public class ChatTestResponse
{
    public bool Success { get; set; }
    public string Request { get; set; } = string.Empty;
    public string? Response { get; set; }
    public string? Error { get; set; }
    public string? ErrorDetails { get; set; }
    public object? RawResponse { get; set; }
}

public class RawQwenTestResponse
{
    public bool Success { get; set; }
    public object? Request { get; set; }
    public object? Response { get; set; }
    public string? Error { get; set; }
    public string? ErrorDetails { get; set; }
}
